package com.av.android;

import java.net.URLEncoder;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ReportDetailActivity extends BaseActivity {
	private static final String[] STATUS = new String[] { "Detected",
		"InProgress","Fixed", "FriendlyLocation" };
	Report report;
	EditText addComment;
	Button up;
	Button down;
	Button subscribe;
	LinearLayout memberButtons;
	TextView reportName;
	TextView createdBy;
	User userOfReport;
	TextView createdDate;
	TextView decription;
	TextView violationType;
	TextView tags;
	List<String> tagList;
	TextView status;
	TextView rate;
	List<ObstacleType> obstacles;
	LinearLayout commentsLayout;
	List<Comment> comments;
	boolean guest = false;
	boolean subscribed=false;
	Button commentbtn;
	TextView commentTitle;
	ImageView reportImage;
	Bitmap bitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report_detail);
		reportImage = (ImageView)findViewById(R.id.report_image);

		commentsLayout=(LinearLayout)findViewById(R.id.comments);
		report = (Report) getIntent().getExtras().getSerializable("report");
		commentbtn = (Button)findViewById(R.id.commentbtn);
		guest = LoginActivity.user ==null;
		commentTitle =(TextView)findViewById(R.id.comments_title);
		addComment=(EditText)findViewById(R.id.add_comment);
		subscribe = (Button)findViewById(R.id.subscribe);
		memberButtons=(LinearLayout)findViewById(R.id.member_buttons);
		reportName=(TextView)findViewById(R.id.report_name);
		createdBy=(TextView)findViewById(R.id.created_by);
		createdDate=(TextView)findViewById(R.id.created_date);
		decription=(TextView)findViewById(R.id.description);
		violationType=(TextView)findViewById(R.id.violation_type);
		tags=(TextView)findViewById(R.id.tags);
		status=(TextView)findViewById(R.id.status);
		rate=(TextView)findViewById(R.id.rate);
		new Thread(new Runnable() {

			public void run() {
				showLoading("");
				// TODO Auto-generated method stub

				bitmap = Utils.getBitmapFromUrl(report.getReport_id()+"_"+1+".jpg");
				if(bitmap==null)
					bitmap = Utils.getBitmapFromUrl(report.getReport_id()+"_"+1+".png");

				if(!guest)
					subscribed = Utils.isSubscribed(LoginActivity.user.getUser_id(), report.getReport_id());
				userOfReport =  Utils.getUser(report.getReport_id());
				obstacles = Utils.GetObstacles();
				tagList = Utils.getTagsOfReport(report.getReport_id());
				comments = Utils.getComments(report.getReport_id());
				runOnUiThread(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub
						hideLoading();
						if(bitmap!=null)
							reportImage.setImageBitmap(bitmap);
						if(subscribed)
							subscribe.setText("Unsubscribe");
						else
							subscribe.setText("Subscribe");
						if(userOfReport!=null)
						createdBy.setText(createdBy.getText()+userOfReport.getUsername());
						if(obstacles!=null)
						violationType.setText(violationType.getText()+obstacles.get((int)(report.getObstacle_id())).toString());
						if(comments!=null)
						setComments();
						String tagsTogether ="";
						if(tagList!=null)
						for(String tag : tagList){
							tagsTogether += "*"+tag+" ";
						}
						tags.setText(tags.getText()+tagsTogether);
					}
				});
			}
		}).start();
		if(guest){

			memberButtons.setVisibility(View.GONE);
			addComment.setVisibility(View.GONE);
			commentbtn.setVisibility(View.GONE);
		}
		reportName.setText(report.getReportName());

		if(report.getCreated_on()!=null)
			createdDate.setText(createdDate.getText()+report.getCreated_on().toLocaleString());
		decription.setText(decription.getText()+report.getDescription());
		status.setText(status.getText()+STATUS[report.getStatus()]);
		rate.setText(rate.getText()+""+report.getRate());

	}
	private void setComments() {


		LayoutInflater inflater= getLayoutInflater();
		if ( comments.size()==0) {
			commentTitle.setVisibility(View.GONE);
		}else{


			for(final Comment comment :comments){
				View commentRow = inflater.inflate(R.layout.comment_row, null);
				TextView commentText = (TextView) commentRow.findViewById(R.id.comment);
				final TextView commentator = (TextView)commentRow.findViewById(R.id.commentator);
				TextView commentdate = (TextView)commentRow.findViewById(R.id.date);
				commentText.setText(comment.getText());
				new Thread(new Runnable() {

					public void run() {
						final String commentatorName = Utils.getUser(comment.getUserId()).getUsername();
						runOnUiThread(new Runnable() {

							public void run() {
								// TODO Auto-generated method stub

								commentator.setText(commentatorName);
							}
						});
					}
				}).start();
				commentdate.setText(comment.getCreatedOn().toLocaleString());
				commentsLayout.addView(commentRow);
			}
		}
	}
	public void up(View v){
		rate("up");
	}
	public void down(View v){
		rate("down");

	}
	private void rate(final String operation) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				showLoading("");
				final String response = Utils.upOrDownRate(operation, report.getReport_id(), LoginActivity.user.getUser_id());
				runOnUiThread(new Runnable() {
					public void run() {
						// TODO Auto-generated method stub
						hideLoading();
						if(response.equals("own")){
							alert("You cannot rate your own report.");
						}else if(response.equals("already")){
							alert("You have already rated.");

						}else if(response.equals("success")){
							alertWithOnClickHandler("Your rate is saved.", "", new Handler(){
								@Override
								public void handleMessage(Message msg){
									startActivity(new Intent(getApplicationContext(), ReportDetailActivity.class).putExtra("report", report));
									finish();
								}
							});

						}
					}
				});
			}
		}).start();
	}
	public void subscribe(View v){
		new Thread(new Runnable() {


			public void run() {
				showLoading("");
				// TODO Auto-generated method stub
				final String response = Utils.subscribe(report.getReport_id(), LoginActivity.user.getUser_id());
				runOnUiThread(new Runnable() {

					public void run() {
						hideLoading();
						// TODO Auto-generated method stub
						if(response.equals("subscribed")){
							alertWithOnClickHandler("You have been subscribed.", "", new Handler(){
								@Override
								public void handleMessage(Message msg){
									startActivity(new Intent(getApplicationContext(), ReportDetailActivity.class).putExtra("report", report));
									finish();
								}
							});
						}else if(response.equals("unsubscribed")){
							alertWithOnClickHandler("You have been unsubscribed.", "", new Handler(){
								@Override
								public void handleMessage(Message msg){
									startActivity(new Intent(getApplicationContext(), ReportDetailActivity.class).putExtra("report", report));
									finish();
								}
							});
						}
					}
				});
			}
		}).start();
	}

	public void saveComment(View v){
		if(addComment.getText().toString().trim().length()==0)
			alert("Enter comment please");
		else{
			new Thread(new Runnable() {

				public void run() {

					showLoading("");// TODO Auto-generated method stub
					final String response = Utils.saveComment(addComment.getText().toString(),report.getReport_id(),LoginActivity.user.getUser_id());
					runOnUiThread(new Runnable() {

						public void run() {
							hideLoading();
							// TODO Auto-generated method stub
							if(response.equals("success"))
								alertWithOnClickHandler("Comment added.", "", new Handler(){
									@Override
									public void handleMessage(Message msg){
										startActivity(new Intent(getApplicationContext(), ReportDetailActivity.class).putExtra("report", report));
										finish();
									}
								});
							else{
								alert("Error occured.");
							}
						}
					});
				}
			}).start();
		}
	}
	public void downloadVideo(View v){
		String url = Utils.URL_PREFIX+"DownloadServlet?path="+URLEncoder.encode(report.getReport_id()+"_1.mp4")
				+"&type=video"+"&reportID="+report.getReport_id();
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(browserIntent);
	}
	public void downloadAudio(View v){
		String url = Utils.URL_PREFIX+"DownloadServlet?path="+URLEncoder.encode(report.getReport_id()+"_1.mp3")
				+"&type=audio"+"&reportID="+report.getReport_id();
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(browserIntent);
	}



}
